package per.qiao.simplerest.proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import per.qiao.simplerest.components.Actuator;

/**
 * Company: 上海数惠系统技术有限公司
 * Department: 数据中心
 * Date: 2020-05-30 14:24
 *
 * @Author: qyp
 * Email: qiaoyp@dist.com.cn
 * Desc:
 */
public class RestServiceBeanFactory<T> implements FactoryBean<T> {

    /**
     * 这里必须用懒加载，因为import进来的类在普通类假如到spring容器中就已经运行了
     * 这里让它调用的时候再注入进来
     */
    @Lazy
    @Autowired
    Actuator actuator;

    private Class<T> interfaceClazz;

    public RestServiceBeanFactory(Class<T> interfaceClazz) {
        this.interfaceClazz = interfaceClazz;
    }

    /**
     * 返回代理对象，第一次惩罚
     *
     * @return
     * @throws Exception
     */
    @Override
    public T getObject() throws Exception {
        return getProxy(new Class[]{interfaceClazz});
    }

    public T getProxy(Class[] clazz){
        Enhancer enhancer = new Enhancer();
        //设置需要创建子类的类
        enhancer.setInterfaces(clazz);
        enhancer.setCallback(new RestMethodInterceptor(actuator));
        //通过字节码技术动态创建子类实例
        return (T) enhancer.create();
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClazz;
    }

}
